package com.heima.kafka.sample;


import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Properties;
import java.util.concurrent.Future;

@SpringBootTest
public class proKafka {
    public static void main(String[] args) {


        //1.kafka的配置信息
        Properties properties=new Properties();
        //kafka的连接地址
        properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.6.104:9092");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);
        //消息key的序列化器
        properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //2.生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);

        //封装发送的消息
        //ProducerRecord<String,String> producerRecord = new ProducerRecord("itheima-topic","100001","hello kafka");

        //3.发送消息
        //Future<RecordMetadata> send = producer.send(producerRecord);
        /**
         * ProducerRecord(String topic, K key, V value)
         * 参数1表示发送消息的主题，也叫队列名称
         * 参数2表示发送消息的key
         参数3表示发送的消息内容
         */
        for (int i = 1; i <=5 ; i++) {
            if(i%2==0){
                ProducerRecord record=new ProducerRecord("kafkastream-topic1","key"+i,"hello kafka");
                producer.send(record);
            }else{
                ProducerRecord record=new ProducerRecord("kafkastream-topic1","key"+i,"hello itcast");
                producer.send(record);
            }

        }
        //4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();

        //3.发送消息

    }
}
